﻿using System;
using System.Collections.Generic;
using System.Text;
//using JYCompress;
using System.IO;
using System.Xml;
//using NAnoto.AFP;
using ICSharpCode.SharpZipLib.Zip;

namespace NAnoto
{
    public class SYMPNGInfo
    {
        public int PageNo=-1;
        public double PageWidth=0;
        public double PageHeight=0;
        public string PngFile=string.Empty;
        public string PageAddress=string.Empty;
    }

    public class SYMInfo
    {
        public Dictionary<int, SYMPNGInfo> lstSYMPNG = new Dictionary<int, SYMPNGInfo>();
        public string SYMTitle;
        public string afdversion;
        public string infoversion;
        public string guid;
        public string backgrounds;
        public string pagestart;
        public string pagestop;
        public string currentcopy;
        public string totalcopies;
        public List<string> lstPageID = new List<string>();
    }
    public class SYMTOAFD
    {
        private string const_zippassword;
        private string sUnZipPath;

        public SYMTOAFD()
        {
            init();
        }

        //手动调用清理
        public void ClearTemp()
        {
            //清理临时文件夹
            Directory.Delete(sUnZipPath, true);
        }

        private void init()
        {
            const_zippassword = "opfdncPG";
        }

        private string GetTempPath()
        {
            //string sTempPath = Environment.CurrentDirectory + "\\TEMP\\" + DateTime.Now.ToString("yyyyMMddHHmmss")+"\\";
            string sTempPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass";
            if (!Directory.Exists(sTempPath))
            {
                Directory.CreateDirectory(sTempPath);
            }
            sTempPath = sTempPath + "\\sym\\";
            if (Directory.Exists(sTempPath))
                Directory.Delete(sTempPath, true);
            if (!Directory.Exists(sTempPath))
            {
                Directory.CreateDirectory(sTempPath);
            }
            return sTempPath;
               
        }
        
        public SYMInfo UNZIPSYM(string FilePath)
        {
            return privateUNZIPSYM(FilePath);
        }
        private SYMInfo privateUNZIPSYM(string FilePath)
        {
            sUnZipPath = GetTempPath();
            FastZip fastZip = new FastZip();
            fastZip.Password = const_zippassword;
            fastZip.ExtractZip(FilePath, sUnZipPath, null);

        //    JYCompress.ZipCompress.DecompressFile(FilePath, sUnZipPath, const_zippassword);
            string sSymFile = sUnZipPath + "sym";
            if (!File.Exists(sSymFile)) return null;
            //JYCompress.ZipCompress.DecompressFile(sSymFile,sUnZipPath);
            fastZip.Password = null;
            fastZip.ExtractZip(sSymFile, sUnZipPath,null);

            string sDocumentMainFile = sUnZipPath + "DocumentMain.afd";
            string sMapInfoFile = sUnZipPath + "PageMapperMain.xml";
            if (!File.Exists(sDocumentMainFile)) return null;
            //JYCompress.ZipCompress.DecompressFile(sDocumentMainFile,sUnZipPath);
            fastZip.ExtractZip(sDocumentMainFile, sUnZipPath, null);

            //先将licenses文件夹删除，防止泄密
            Directory.Delete(sUnZipPath + "licenses\\",true);

            string sMainDocumentFile = sUnZipPath + "main.document";
            string sMainInfoFile = sUnZipPath + "main.info";
            //string sPageMapperMainXMLFile = sUnZipPath + "PageMapperMain.xml";

            StreamReader reader = new StreamReader(sMainInfoFile, System.Text.Encoding.UTF8);
            string line;
            SYMInfo ASYMInfo = new SYMInfo();
            while ((line = reader.ReadLine()) != null)
            {
                if (line.StartsWith("title"))
                {
                    ASYMInfo.SYMTitle = line.Substring(line.IndexOf(":") + 1).Trim();
                }
                else if (line.StartsWith("afdversion"))
                {
                    ASYMInfo.afdversion = line.Substring(line.IndexOf(":") + 1).Trim();
                }
                else if (line.StartsWith("infoversion"))
                {
                    ASYMInfo.infoversion = line.Substring(line.IndexOf(":") + 1).Trim();
                }
                else if (line.StartsWith("guid"))
                {
                    ASYMInfo.guid = line.Substring(line.IndexOf(":") + 1).Trim();
                }
                else if (line.StartsWith("backgrounds"))
                {
                    ASYMInfo.backgrounds = line.Substring(line.IndexOf(":") + 1).Trim();
                }
                else if (line.StartsWith("pagestart"))
                {
                    ASYMInfo.pagestart = line.Substring(line.IndexOf(":") + 1).Trim();
                }
                else if (line.StartsWith("pagestop"))
                {
                    ASYMInfo.pagestop = line.Substring(line.IndexOf(":") + 1).Trim();
                }
                else if (line.StartsWith("currentcopy"))
                {
                    ASYMInfo.currentcopy = line.Substring(line.IndexOf(":") + 1).Trim();
                }
                else if (line.StartsWith("totalcopies"))
                {
                    ASYMInfo.totalcopies = line.Substring(line.IndexOf(":") + 1).Trim();
                }
            }
            reader.Close();

            XmlDocument MainDocument = new XmlDocument();
            XmlReaderSettings AxmlReaderSettings = new XmlReaderSettings();
            AxmlReaderSettings.IgnoreComments = true;
            XmlReader AXmlReader = XmlReader.Create(sMainDocumentFile, AxmlReaderSettings);
            MainDocument.Load(AXmlReader);
            XmlNode xn = MainDocument.SelectSingleNode("document");
            XmlNodeList xnl = xn.ChildNodes;
            string PageAddress = ASYMInfo.pagestart;
            foreach (XmlNode xn1 in xnl)
            {
                SYMPNGInfo ASYMPNGInfo = new SYMPNGInfo();
                XmlElement xe = (XmlElement)xn1;
                // 得到Type和ISBN两个属性的属性值
                ASYMPNGInfo.PageHeight = Convert.ToDouble(xe.GetAttribute("height").ToString());
                ASYMPNGInfo.PageWidth = Convert.ToDouble(xe.GetAttribute("width").ToString());
                ASYMPNGInfo.PageAddress = PageAddress;
                //PageAddress = AddPageID(PageAddress);
                PageAddress = AddPageAddres(PageAddress, 1);
                string sPageNO = xe.GetAttribute("basepath").ToString();
                ASYMPNGInfo.PageNo = Convert.ToInt32(sPageNO.Substring(sPageNO.IndexOf("/") + 1));
                ASYMPNGInfo.PngFile = sUnZipPath + "backgrounds\\page" + ASYMPNGInfo.PageNo.ToString() + "_" + ASYMInfo.backgrounds + ".png";
                if (!File.Exists(ASYMPNGInfo.PngFile))
                {
                    ASYMPNGInfo.PngFile = string.Empty;
                }
                ASYMInfo.lstSYMPNG.Add(ASYMPNGInfo.PageNo, ASYMPNGInfo);
            }
            AXmlReader.Close();


            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(sMapInfoFile);
            XmlNodeList topM = xmldoc.DocumentElement.ChildNodes;
            foreach (XmlElement element in topM)
            {
                if (element.Name == "Resource")
                {
                    XmlNodeList innerList = element.ChildNodes;
                    foreach (XmlElement item in innerList)
                    {
                        if (item.Name == "FileName")
                            ASYMInfo.SYMTitle = item.Value;
                    }
                }
            }
            return ASYMInfo;
        }

        private string AddPageID(string PageAddressIP)
        {
            ulong uPageID = 0;
            //pageaddress.paDeserializePA(PageAddressIP, ref uPageID);
            uPageID = uPageID + 1;
            StringBuilder izText = new StringBuilder("");
            //pageaddress.paSerializePA(izText, uPageID);
            return izText.ToString();

        }
        private string AddPageAddres(string basePage, int index)
        {
            string[] parts = basePage.Split('.');
            int section = Convert.ToInt32(parts[0]);
            int shelf = Convert.ToInt32(parts[1]);
            int book = Convert.ToInt32(parts[2]);
            int page = Convert.ToInt32(parts[3]);
            page += index;
            if (section == 1713 && page > 107)
            {
                book++;
                page -= 108;
                if (book > 52)
                {
                    shelf++;
                    book = 0;
                }
            }
            if (section == 1536 && page > 107)
            {
                book++;
                page -= 108;
                if (book > 72)
                {
                    shelf++;
                    book = 0;
                }
            }
            return string.Format("{0}.{1}.{2}.{3}", section, shelf, book, page);
        }
    }
}
